<template>
  <div>
    <div v-show="!isHidden"
      style="background-color: #fff; height: 100%; width:265px; border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);"
      :style="{ minHeight: minHeight }" class="content" :class="{ 'hidden': isHidden }">
      <div style="position: relative;">
        <div style="display:flex;justify-content:space-around;align-items:center;padding:12px 0px;background:#f3f6fa;"
          v-show="HasTreeClass">
          <el-link :type="this.TreeClass === 1 ? 'primary' : 'info'" :underline="false" @click="TreeClassClick(1)"
            :class="{link_underline: this.TreeClass === 1}">项目分类</el-link>
          <!-- <el-divider direction="vertical"></el-divider> -->
          <el-link :type="this.TreeClass === 2 ? 'primary' : 'info'" :underline="false" @click="TreeClassClick(2)"
            :class="{link_underline: this.TreeClass === 2}">安全等级</el-link>
        </div>
        <el-tree node-key="Name" ref="myTree" :data="nodeData" :current-node-key="choseNode" :defaultExpandAll="defaultExpandAll"
          :highlight-current="true" :expand-on-click-node="false" :default-expanded-keys="expandArray"
          @node-click="handleNodeClick" :props="defaultProps" style="width:260px;overflow-x:auto;">
          <span slot-scope="{ node }" style="width: 90%;overflow-x:auto;">
            <span class="blue-on-hover" style="display: flex; align-items: center;" @mouseover="node.data.edit = true"
              @mouseleave="node.data.edit = false">
              <div v-show="node.level === 1"
                style="width:100%;display: flex;justify-content: space-between;align-items: center;">
                <span
                  style="font-size:15px;font-family: Verdana;display:inline-block; white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"
                  :title="node.label">{{ node.label }}</span>
                <el-button type="text" style="padding-right:10px;" @click.stop="addNew"
                  v-show="node.level === 1 && addTemplate">{{ `${dialogName}编辑` }}</el-button>
                <span style="float:right;margin-right:15px;color: #c2c2c2;" v-show="!node.data.edit && !addTemplate">
                  {{ node.data.Count }}
                </span>
              </div>
              <div v-show="node.level > 1"
                style="align-items: center;justify-content: space-between;width: 100%;font-size:14px">
                <span v-show="!node.data.Children || node.data.Children.length === 0" style="width: 7px;height: 7px;border-radius: 50%;background-color: #e5e5e5;display: inline-block;margin-right: 5px;"></span>
                <el-tooltip effect="dark" :content="node.label" placement="left" v-show="node.label.length > 8"
                  style="display:inline-block">
                  <span class="ellipsis">{{ node.label }}</span>
                </el-tooltip>
                <span v-show="node.label.length <= 8">{{ node.label }}</span>
                <span style="float:right;margin-right:15px;color: #c2c2c2;"
                  v-show="(!node.data.edit && dialogName !== '部门')">
                  {{ node.data.Count }}
                </span>
                <span style="float:right;margin-right:15px;color: #c2c2c2;"
                  v-show="(!node.data.edit && dialogName === '部门' && node.data.OnlineCount >= 0)">
                  {{ node.data.OnlineCount }} / {{ node.data.OnlineCount + node.data.OffLineCount }}
                </span>
              </div>
              <i class="el-icon-delete" style="margin-right:15px;font-size:13px;" slot="reference"
                @click="deleteItem(node)" v-show="node.level > 1 && node.data.edit" />
            </span>
          </span>
          <span></span>
        </el-tree>
      </div>
    </div>
    <div class="ssb-eh__close" v-show="!isHidden">
      <i class="el-icon-arrow-left" @click.stop="toggleVisibility" />
    </div>
    <div class="ssb-eh__close" v-show="isHidden">
      <i class="el-icon-arrow-right" @click.stop="toggleVisibility" />
    </div>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :title="`${dialogName}编辑`"
      :visible.sync="moderVisible" v-el-drag-dialog width="40%">
      <el-form label-width="120px" :rules="rules" :model="partition" ref="partition">
        <div style="display:flex;">
          <el-button type="primary" icon="el-icon-plus" @click="addDepartment" size="mini">添加子{{ dialogName }}</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteDepartment" size="mini"
            :disabled="!this.Name || hasChildren">删除</el-button>
        </div>
        <el-divider></el-divider>
        <el-tree node-key="Name" :data="nodeData" :current-node-key="choseNode" :defaultExpandAll="defaultExpandAll"
          :highlight-current="true" :expand-on-click-node="false" :default-expanded-keys="expandArray"
          :props="defaultProps" @node-click="NodeClick" style="width:100%;height:400px;overflow-y:auto">
          <span slot-scope="{ node }" style="width: 90%;">
            <span class="blue-on-hover" style="display: flex; align-items: center;">
              <div v-show="node.level === 1"
                style="width:100%;display: flex;justify-content: space-between;align-items: center;">
                <span style="font-size:15px;font-family: Verdana;display:inline-block">{{ node.label }}</span>
              </div>
              <div v-show="node.level > 1"
                style="align-items: center;justify-content: space-between;width: 100%;font-size:14px">
                <span
                  style="width: 7px;height: 7px;border-radius: 50%;background-color: #e5e5e5;display: inline-block;margin-right: 5px;"></span>
                <el-tooltip effect="dark" :content="node.label" placement="left" v-show="node.label.length > 10"
                  style="display:inline-block">
                  <span class="ellipsis">{{ node.label }}</span>
                </el-tooltip>
                <span v-show="node.label.length <= 10">{{ node.label }}</span>
              </div>
            </span>
          </span>
        </el-tree>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="moderVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
      :title="Action === 1 ? `新增${dialogName}` : `修改${dialogName}`" :visible.sync="departmentDialog" v-el-drag-dialog
      width="30%">
      <el-form label-width="120px" :rules="rules" :model="partition" ref="partition">
        <el-form-item :label="`上级${dialogName}`" prop="ParentID" v-show="dialogName === '部门'">
          <el-cascader v-model="partition.ParentID" ref="cascaderAddr" :placeholder="`请选择上级${dialogName}`"
            :options="nodeData"
            :props="{ children: 'Children', label: 'Name', value: 'ID', checkStrictly: true, emitPath: false, expandTrigger: 'hover' }"
            clearable @expand-change="elCascaderOnlick" @visible-change="elCascaderOnlick" @change="departmentChange"
            style="width: 100%;">
          </el-cascader>
        </el-form-item>
        <el-form-item :label="`${dialogName}名称`" prop="DepartmentName">
          <el-input :placeholder="`请输入${dialogName}名称`" maxlength="7" v-model="partition.DepartmentName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="departmentDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from '@/api/firstPage'
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import draggable from 'vuedraggable'
export default {
  directives: { elDragDialog },
  components: { draggable },
  props: {
    nodeData: {
      type: Array,
      default() {
        return []
      }
    },
    DepartmentList: {
      type: Array,
      default() {
        return []
      }
    },
    addTemplate: {
      type: Boolean,
      default() {
        return true
      }
    },
    choseNode: {
      type: String,
      default() {
        return null
      }
    },
    defaultExpandAll: {
      type: Boolean,
      default() {
        return true
      }
    },
    expandArray: {
      type: Array,
      default() {
        return []
      }
    },
    defaultProps: {
      type: Object,
      default() {
        return {
          children: 'Children',
          label: 'Name',
          Count: 'Count'
        }
      }
    },
    dialogName: {
      type: String,
      default() {
        return '部门'
      }
    },
    minHeight: {
      type: String,
      default: 'calc(100vh - 70px)'
    },
    HasTreeClass: {
      type: Boolean,
      default() {
        return false
      }
    },
    TreeClass: {
      type: Number,
      default() {
        return 1
      }
    },
  },
  data() {
    return {
      Action: 1,
      moderVisible: false,
      departmentDialog: false,
      isHidden: false,
      hasChildren: false,
      Name: '',
      RootName: '',
      rules: {
        DepartmentName: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      partition: {},
      clickNode: {}
    }
  },
  methods: {
    changeHighlightCurrent(Name){
      this.$nextTick(() => {
        this.$refs.myTree.setCurrentKey(Name);
      });
    },
    handleNodeClick(data, node) {
      this.$emit('handleNodeClick', { data, node })
    },
    NodeClick(data, node) {
      this.hasChildren = ((this.dialogName === '部门' && !data.Children && (data.OffLineCount + data.OnlineCount === 0)) || data.Count === 0) ? false : true;
      this.Name = data.Name
      this.RootName = data.RootName
      this.clickNode = data
      if (this.dialogName === '部门') {
        if (data.disabled) {
          this.$set(this.partition, 'ParentID', data.ParentID || 0)
          this.$set(this.partition, 'ParentName', data.ParentName || "")
        } else {
          this.$set(this.partition, 'ParentID', data.ID || 0)
          this.$set(this.partition, 'ParentName', data.Name || "")
        }
      }
    },
    departmentChange(row) {
      this.$set(this.partition, 'ParentID', row || 0)
      this.$set(this.partition, 'ParentName', this.DepartmentList.find(item => item.ID === row)?.Name || '')
    },
    addDepartment() {
      this.departAction = 1
      this.partition = this.partition?.ParentID ? { ...this.partition, DepartmentName: '' } : { ParentID: 0, ParentName: '' }
      this.departmentDialog = true
    },
    deleteDepartment() {
      this.$confirm(`此操作将永久删除该${this.dialogName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (this.dialogName === '部门') {
          const data = {
            Data: {
              DepartmentName: this.clickNode.Name,
              ParentName: this.clickNode.ParentName,
              ID: this.clickNode.ID,
              ParentID: this.clickNode.ParentID
            }
          }
          const res = await connrequest('DelDepartment', data)
          if (res.Status.StatusCode === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.$emit('addDepartment')
          }
        } else {
          this.$emit('deleteNode', this.clickNode)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async addNew() {
      await this.$emit('addDepartment')
      this.Action = 1
      this.partition = {},
        this.$nextTick(() => {
          this.$refs.partition.clearValidate();
        })
      this.moderVisible = true
    },
    editItem(Name) {
      this.Action = 2
      this.$set(this.partition, 'Name', Name)
      this.$nextTick(() => {
        this.$refs.partition.clearValidate();
      })
      this.moderVisible = true
    },
    deleteItem(node) {
      this.$confirm(`此操作将永久删除该${this.dialogName}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('deleteNode', node.data)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submit() {
      this.$refs['partition'].validate(async (valid) => {
        if (valid) {
          if (this.dialogName === '部门') {
            if (!this.partition.DepartmentName) {
              this.$message.error('请输入部门名称')
              return false
            }
            const data = {
              Data: {
                ParentID: this.partition.ParentID || 0,
                ParentName: this.Name,
                DepartmentName: this.partition.DepartmentName
                // ID: Math.floor(Date.now() / 1000)
              }
            }
            const res = await connrequest('AddDepartment', data)
            if (res.Status.StatusCode === 0) {
              this.$message.success('新增部门成功')
              this.departmentDialog = false
              this.$emit('addDepartment')
            }
          } else {
            this.$emit('submitTemplete', { ...this.partition, Action: this.Action })
          }
        } else {
          return false;
        }
      })
    },
    TreeClassClick(TreeClass){
      this.$emit('TreeClassClick', TreeClass)
    },
    toggleVisibility() {
      this.isHidden = !this.isHidden;
      this.$emit('toggleVisibility', this.isHidden)
    },
    elCascaderOnlick() {
      let that = this;
      setTimeout(function () {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function () {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    }
  }
}
</script>
<style lang="scss" scoped>
.link_underline{
  position: relative; /* 为伪元素定位提供参考 */
  display: inline-block; /* 确保元素宽度适应文字 */
}
.link_underline::after {
  content: '';
  position: absolute;
  left: 25%; /* 线条左端缩进，使线条比文字短 */
  bottom: -12px; /* 线条与文字的间距 */
  width: 50%; /* 线条宽度为文字宽度的50% */
  height: 3px; /* 线条粗细 */
  border-radius: 5px;
  background-color: #2491fc; /* 线条颜色 */
}
::v-deep .el-tree-node__content {
  height: 38px;
  line-height: 38px;
  font-size: 15px;
}

.blue-on-hover:hover {
  color: #62bfff;
  /* cursor: pointer; */
}

.content {
  animation: fadeInOut 0.5s ease;
  /* 动画名称、持续时间、过渡曲线 */
  width: 240px;
  /* 初始状态 */
}

.hidden {
  animation: fadeInOut 0.5s ease;
  /* 动画名称、持续时间、过渡曲线 */
  width: 240px;
  /* 初始状态 */
}

@keyframes fadeInOut {
  0% {
    opacity: 240px;
    /* 起始状态 */
  }

  100% {
    opacity: 0px;
    /* 结束状态 */
  }
}

.ssb-eh__close {
  width: 20px;
  flex: 0 0 20px;
  text-align: center;
  line-height: 32px;
  background: #FFFFFF;
  box-shadow: 4px 0 16px 1px #3634651a;
  border-radius: 0 6px 6px 0;
  border: 1px solid #E5E5E5;
  border-left: none;
  cursor: pointer;
  color: #141414;
  top: 350px;
  left: 11px;
  height: 30px;
  position: absolute;
  z-index: 10;
}

/* 限制文本宽度为 5 个字，超出部分显示省略号 */
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 14px;
  width: 6em !important;
  /* 一个汉字宽度约为 1em，可以根据需要调整宽度 */
}
</style>
